package cn.com.haopy.yue.ai.wx.service;


import cn.com.haopy.yue.ai.core.config.ChatApiProperties;
import cn.com.haopy.yue.ai.core.executor.ExecutorCore;
import cn.com.haopy.yue.ai.core.executor.ExecutorScheduledCore;
import cn.com.haopy.yue.ai.db.entity.arisk.*;
import cn.com.haopy.yue.ai.db.service.hos.*;
import cn.com.haopy.yue.ai.wx.dto.AIChartMsgResponseDto;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * 输入异常项或者是指标，得出可能得疾病
 *
 * @author keel
 * @date 2022/4/13
 */
@Service
@Slf4j
public class WxPapersDrugsService {


    @Autowired
    private ChatAiApiService chatAiApiService;

    @Autowired
    private ChatApiProperties chatProperties;

    @Autowired
    private AIRiskPapersService riskPapersService;

    @Autowired
    private AIRiskPapersIndexService riskPapersIndexService;

    @Autowired
    private AIRiskPapersIllnessService riskPapersIllnessService;

    @Autowired
    private AIRiskPapersDrugsService riskPapersDrugsService;

    @Autowired
    private AIRiskIllnessDrugsService riskIllnessDrugsService;

    @Autowired
    AIRiskIllnessService riskIllnessService;


    @Async
    public void recommendDrugsByPaperId(Integer paperId) throws Exception {

        try {
            System.out.println("开始执行药品推荐");
            ExecutorScheduledCore.getExecutorService().schedule(() -> {


                AIRiskPapers paper = riskPapersService.getById(paperId);

                System.out.println("开始执行药品推荐");


                List<AIRiskPapersIndex> papersIndexList = riskPapersIndexService.getNotEmptyByPapersId(paperId);
                String query = "年龄，实际值：" + paper.getAge() + " 岁。";
                for (AIRiskPapersIndex paperIndex : papersIndexList) {
                    if (paperIndex.getIndexName().equals("年龄")) {
                        continue;
                    }
                    if (StringUtils.hasText(paperIndex.getIndexValue())) {
                        query += paperIndex.getIndexName() + "，实际值：" + paperIndex.getIndexValue() + "。";
                    }
                }

                System.out.println(query.length());
                if (query.length() > 512) {
                    query = query.substring(0, 512);
                }
                System.out.println(query.length());


                //查询疾病--
                //List<AIRiskPapersIllness> papersIllnessList = riskPapersIllnessService.getByPapersId(paperId);
                Short sex = Short.valueOf("0");
                if (paper.getSex().equals("男")) {
                    sex = Short.valueOf("1");
                }
                if (paper.getSex().equals("女")) {
                    sex = Short.valueOf("1");
                }

                List<AIRiskIllness> listIllness = riskIllnessService.listActiveSex(sex);


                for (AIRiskIllness illnessItem : listIllness) {
                    Map<String, Object> input_params = new HashMap<>();
                    input_params.put("input", illnessItem.getQuestion());


                    String finalQuery = query;
                    ExecutorCore.execute(() -> {


                        try {
                            AIChartMsgResponseDto msgResponseDto = chatAiApiService.chatMessage(paperId + "", "", input_params, finalQuery, chatProperties.getPreDrugsKey());
                            //保存推荐药品
                            saveDrugsRecommend(paperId, illnessItem.getId(), msgResponseDto);
                        } catch (Exception e) {
                            log.error(e.toString());
                        }


                    });


                }

            }, 2, TimeUnit.SECONDS);


        } catch (Exception e) {
            log.error(e.toString());
        }


    }


    public void saveDrugsRecommend(Integer paperId, Integer illnessId, AIChartMsgResponseDto msgResponseDto) {
        try {
            AIRiskPapersDrugs drugs = new AIRiskPapersDrugs();
            drugs.setPaperId(paperId);
            drugs.setIllnessId(illnessId);
            try {
                String answer = msgResponseDto.getAnswer();
                Gson gson = new Gson();
                drugs.setDrugNames(gson.fromJson(answer, String[].class));
            } catch (Exception e) {
                log.error(e.toString());
            }

            riskPapersDrugsService.save(drugs);

        } catch (Exception e) {
            log.error(e.toString());
        }


    }

    public List<String> getDrugsByPaperId(Integer paperId) {
        List<AIRiskPapersDrugs> paperDrugs = riskPapersDrugsService.getByPaperId(paperId);
        List<String> list = new ArrayList<>();
        for (AIRiskPapersDrugs item : paperDrugs) {
            list.addAll(Arrays.asList(item.getDrugNames()));
        }
        // 去重（顺序可能改变）
        Set<String> set = new HashSet<>(list);
        List<String> uniqueList = new ArrayList<>(set);

        return uniqueList;

    }


    @Async
    public void recommendDrugsByPaperIdNew(Integer paperId) throws Exception {

        try {
            System.out.println("开始执行药品推荐");
            ExecutorScheduledCore.getExecutorService().schedule(() -> {


                List<AIRiskPapersIllness> listIllness = riskPapersIllnessService.getByPapersId(paperId);


                for (AIRiskPapersIllness illnessItem : listIllness) {
                    List<AIRiskIllnessDrugs> illnessDrugs = riskIllnessDrugsService.getByIllnessId(illnessItem.getIllnessId());

                    ExecutorCore.execute(() -> {

                        List<String> drugsNames = new ArrayList<>();

                        illnessDrugs.forEach(item -> {
                            drugsNames.add(item.getDrugName());
                        });

                        try {
                            AIRiskPapersDrugs paperDrugs = new AIRiskPapersDrugs();
                            paperDrugs.setPaperId(paperId);
                            paperDrugs.setIllnessId(illnessItem.getIllnessId());
                            paperDrugs.setDrugNames(drugsNames.toArray(new String[drugsNames.size()]));
                            riskPapersDrugsService.save(paperDrugs);

                        } catch (Exception e) {
                            log.error(e.toString());
                        }


                    });


                }

            }, 4, TimeUnit.SECONDS);


        } catch (Exception e) {
            log.error(e.toString());
        }


    }


}
